<?php
namespace app\platform\controller\admin;
use app\BaseController;
use app\common\logic\cloud\BaseCloudLogic;
use app\common\logic\cloud\FrameCloudLogic;
use app\common\logic\cloud\PhpCodeCloudLogic;
use app\common\logic\cloud\MiniappCloudLogic;
use app\common\logic\DataSettingLogic;
use app\common\helper\open\OpenPlatformMiniappCodeHelper;
use app\common\model\AppModel;
use app\common\model\AppVersionModel;
use think\facade\Db;
use ZipArchive;
class Cloud extends BaseController{
    
    public function initData(){
        try{
            $BaseCloudLogic = new BaseCloudLogic();
            $res = $BaseCloudLogic->initData();
            $res['myapps'] = AppModel::select()->append(['add_time_format'])->toArray();
            return $this->success($res);
        } catch (\think\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    //注册并激活站点
    public function register(){
        $name = $this->request->param('name');
        $site_name = $this->request->param('site_name');
        $mobile = $this->request->param('mobile');
        if(empty($name) || empty($site_name) || empty($mobile)){
            return $this->error('请认真填写激活资料');
        }
        try{
            $BaseCloudLogic = new BaseCloudLogic();
            $res = $BaseCloudLogic->register([
                'name' => $name,
                'mobile' => $mobile,
                'site_name' => $site_name
            ]);
            if($res['auth'] == ''){
                return $this->error('获取激活码失败');
            }
            file_put_contents(root_path().'auth.txt', $res['auth']);
            return  $this->success('激活成功');
        } catch (\think\Exception $e){
            return $this->error($e->getMessage());
        }       
    }
    
    public  function getFrameV(){
         try{
            $FrameCloudLogic = new FrameCloudLogic();
            $res = $FrameCloudLogic->getFrameV();
            return $this->success($res);
         }catch (\think\Exception $e){
            return $this->error($e->getMessage());
        }   
    }
    
    public function getFrameFile(){
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        try{
            $FrameCloudLogic = new FrameCloudLogic();
            $res = $FrameCloudLogic->getFrameFile($v);
            if($res == true){
                return $this->success('下载文件成功');
            }else{
                return $this->error('下载文件失败');
            }
         }catch (\think\Exception $e){
            return $this->error($e->getMessage());
        }   
    }
    //解压文件
    public function decompressionFrameFile(){
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'frame/'.$v;
        $file = $dir.'/'.$v.'.zip';
        $zip=new ZipArchive;//新建一个ZipArchive的对象 
        if($zip->open($file)===TRUE){ 
            $zip->extractTo($dir); 
            $zip->close();
            unlink($file);
            $jsdir = [
                $dir .'/account/js/',
                $dir.'/admin/js/',
            ];
            $domain = $_SERVER['HTTP_HOST'];
            foreach($jsdir as $d){
                if(is_dir($d)){
                    $files = scandir($d);
                    foreach($files as $val){
                        if(strstr($val,'.js')){
                            $str = file_get_contents($d.$val);
                            $str = preg_replace('/api\.boyanhy\.com/',$domain, $str);
							$str = preg_replace('/127\.0\.0\.1:9093/',$domain, $str);
                            $str = preg_replace('/www\.boyanhy\.com/',$domain, $str);
                            $str = preg_replace('/store\.boyanhy\.cloud/',$domain, $str);
                            file_put_contents($d.$val, $str);
                        }
                    }
                }
            }
            return $this->success('解压文件成功');
        }else{
            return $this->error('解压文件失败');
        }         
    }
    
    //移动文件
    public function moveFrameFile(){
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'frame/'.$v;
        $phpdir = $dir.'/php/';
        $accountDir = $dir.'/account/';
        $adminDir = $dir.'/admin/';
        if(is_dir($phpdir)){
            $res = doMoveDir($phpdir, root_path());
            if($res == false) return $this->error ('复制PHP文件失败');
        }
        if(is_dir($accountDir)){
            $res = doMoveDir($accountDir, root_path().'public/account/');
            if($res == false) return $this->error ('复制商户管理文件失败');
        }
        if(is_dir($adminDir)){
            $res = doMoveDir($adminDir, root_path().'public/admin/');
            if($res == false) return $this->error ('复制后台管理文件失败');
        }
        return $this->success('复制文件成功');
    }
    
    public function installFrameSql(){
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $sqlFile = root_path().'frame/'.$v.'/update.sql';
        if(!file_exists($sqlFile)){
            return $this->success('执行成功');
        }
       
        $sql = file_get_contents($sqlFile);
        $sqls = explode(';'."\r", $sql);
        if(empty($sql)) return $this->success ('执行成功');
        Db::startTrans();
        try{
            foreach($sqls as $val){
               $val = trim($val);
               if(!empty($val)){
                  Db::execute($val);
               }
            }
            Db::commit();
            return $this->success ('执行成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    public function overFrame(){
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $FrameCloudLogic = new FrameCloudLogic();
        try{
            $res = $FrameCloudLogic->overFrameUpdate($v);
            return $this->success('升级成功');
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    
    public function getPhpCodeV(){
        $appId = $this->request->param('appId/d');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $PhpCodeCloudLogic = new PhpCodeCloudLogic();
        try{
             $res = $PhpCodeCloudLogic->getPhpCodeV([
                 'appId'=>$appId,
             ]);
             return $this->success($res);
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    
    public function getPhpCodeFile(){
        $appId = $this->request->param('appId/d');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('请选择版本');
        }
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $PhpCodeCloudLogic = new PhpCodeCloudLogic();
        try{
           $res = $PhpCodeCloudLogic->getPhpCodeFile([
                 'appId'=>$appId,
                 'v' => $v,
                 'iden' => $iden,
             ]);
           if($res == false){
               return $this->error('下载失败');
           }
           return $this->success('下载成功');
            
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    
       //解压文件
    public function decompressionPhpFile(){
        $appId = $this->request->param('appId/d');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        $file = $dir.'/'.$v.'.zip';
        $zip=new ZipArchive;//新建一个ZipArchive的对象 
        if($zip->open($file)===TRUE){ 
            $zip->extractTo($dir); 
            $zip->close();
            unlink($file);
            $jsdir = [
                $dir .'/manage/js/',
                $dir.'/manage/cashier/js/'
            ];
            $domain = $_SERVER['HTTP_HOST'];
            foreach($jsdir as $d){
                if(is_dir($d)){
                    $files = scandir($d);
                    foreach($files as $val){
                        if(strstr($val,'.js')){
                            $str = file_get_contents($d.$val);
                            $str = preg_replace('/api\.boyanhy\.com/',$domain, $str);
                            $str = preg_replace('/www\.boyanhy\.com/',$domain, $str);
                            $str = preg_replace('/127\.0\.0\.1:9093/',$domain, $str);
                            $str = preg_replace('/store\.boyanhy\.cloud/',$domain, $str);
                            file_put_contents($d.$val, $str);
                        }
                    }
                }
            }
            return $this->success('解压文件成功');
        }else{
            return $this->error('解压文件失败');
        }         
    }
    
    public function movePhpFile(){
        $appId = $this->request->param('appId/d');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        $phpdir = $dir.'/php/';
        $manageDir = $dir.'/manage/';
        if(is_dir($phpdir)){
            $res = doMoveDir($phpdir, root_path().'app/'.$iden.'/');
            if($res == false) return $this->error ('复制应用PHP文件失败');
        }
        if(is_dir($manageDir)){
            $res = doMoveDir($manageDir, root_path().'public/'.$iden.'/');
            if($res == false) return $this->error ('复制应用后台文件失败');
        }
    
        return $this->success('复制文件成功');
    }
    
     public function installPhpSql(){
        $appId = $this->request->param('appId/d');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('要升级的版本不正确');
        }
        $dir = root_path().'phpCode/'.$iden.'/'.$v;
        $install = $this->request->param('install/d');
        if($install == 0){ //安装SQL
            $sqlFile = $dir.'/install.sql';
        }else{ //更新操作
            $sqlFile = $dir.'/update.sql';
        }
        if(!file_exists($sqlFile)){
            return $this->success('执行成功');
        }
       
        $sql = file_get_contents($sqlFile);
        $sqls = explode(';'."\r", $sql);
        if(empty($sql)) return $this->success ('执行成功');
        Db::startTrans();
        try{
            foreach($sqls as $val){
               $val = trim($val);
               if(!empty($val)){
                  Db::execute($val);
               }
            }
            Db::commit();
            return $this->success ('执行成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    public function overPhpUpdate(){
        $appId = $this->request->param('appId/d');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('请选择版本');
        }
        $iden = $this->request->param('iden');
        if(empty($iden)){
            return $this->error('应用参数不存在');
        }
        $PhpCodeCloudLogic = new PhpCodeCloudLogic();
        try{
            $res = $PhpCodeCloudLogic->overPhpUpdate([
                'appId' => $appId,
                'v'     => $v,
            ]);
            if(null === AppModel::where([['iden','=',$iden]])->find()){ //写入我的APP中
                $app = new AppModel();
                $app->name = $this->request->param('name');
                $app->logo = $this->request->param('logo');
                $app->type = $this->request->param('type');
                $app->iden = $this->request->param('iden');
                $app->production_address = 'https://'.$_SERVER['HTTP_HOST'].'/'.$iden.'#/';
                $app->development_address = 'https://'.$_SERVER['HTTP_HOST'].'/'.$iden.'#/';
                $app->trial_days = 7;
                $app->sku = [
                    ['num'=>1,'unit'=>3,'base_price'=>500,'price'=>500,'discount'=>10],
                    ['num'=>2,'unit'=>3,'base_price'=>1000,'price'=>800,'discount'=>8],
                    ['num'=>3,'unit'=>3,'base_price'=>1500,'price'=>1000,'discount'=>6.7],
                ];
                $app->scene = $this->request->param('scene');
                $app->status = 0; //开发中
                $app->save();
            }
            return $this->success('安装成功');
        }
        catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
        
    public function getMiniappV(){
        $DataSettingLogic = new DataSettingLogic();
        $setting = $DataSettingLogic->getData('open');
        if(empty($setting['miniapp_id']) || empty($setting['miniapp_auth'])){
            return $this->error('暂未配置开发的小程序及小程序上传秘钥');
        }
        $appId = $this->request->param('appId');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $MiniappCloudLogic = new MiniappCloudLogic();
        try{
            $res = $MiniappCloudLogic->getMiniappV(['appId'=>$appId]);
            return $this->success($res);
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    
    public function planMiniappResource(){
        $appId = $this->request->param('appId');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $DataSettingLogic = new DataSettingLogic();
        $setting = $DataSettingLogic->getData('open');
        if(empty($setting['miniapp_id']) || empty($setting['miniapp_auth'])){
            return $this->error('暂未配置开发的小程序及小程序上传秘钥');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('暂时没有要更新的版本');
        }
        $MiniappCloudLogic = new MiniappCloudLogic();
        try{
            $res = $MiniappCloudLogic->planMiniappResource([
                'appId'=>$appId,
                'v'    => $v,
                'wxAppId' => $setting['miniapp_id'],
                'wxUploadKey' =>$setting['miniapp_auth'],
            ]);
            return $this->success($res);
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    
    public function uploadMiniapp(){
        $DataSettingLogic = new DataSettingLogic();
        $setting = $DataSettingLogic->getData('open');
        if(empty($setting['miniapp_id'])){
            return $this->error('暂未配置开发的小程序');
        }
        $MiniappCloudLogic = new MiniappCloudLogic();
        try{
            $res = $MiniappCloudLogic->uploadMiniapp([
                'wxAppId' => $setting['miniapp_id'],
            ]);
            return $this->success('上传成功');
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    
    public function createFromDraft(){
        $OpenPlatformMiniappCodeHelper = new OpenPlatformMiniappCodeHelper();
//        $res = $OpenPlatformMiniappCodeHelper->getTemplateList();
//        var_dump($res);
        $res = $OpenPlatformMiniappCodeHelper->getDrafts();
        if(empty($res['draft_list'])){
            return $this->error('第三方开放平台草稿箱没有草稿,应该上传小程序故障了');
        }
        $draft_id = $res['draft_list'][count($res['draft_list']) - 1]['draft_id'];
        if(empty($draft_id)){
            return $this->error('第三方开放平台草稿箱没有草稿,应该上传小程序故障了');
        }
        $res = $OpenPlatformMiniappCodeHelper->createFromDraft($draft_id);
        if($res['errcode'] != 0){ //如果失败直接报错
            return $this->error($res['errmsg']);
        }
        $list = $OpenPlatformMiniappCodeHelper->getTemplateList();
        if($list['errcode'] != 0){
            return $this->error($res['errmsg']);
        }
        $template_id = $list['template_list'][count($list['template_list']) - 1]['template_id'];
        return $this->success(['template_id'=>$template_id]);
    }
    
    public function overMiniapp(){
        $appId = $this->request->param('appId/d');
        if(empty($appId)){
            return $this->error('应用不存在');
        }
        $v = $this->request->param('v');
        if(empty($v)){
            return $this->error('请选择版本');
        }
        $desc = $this->request->param('desc');
        $desc = preg_replace('/<br\\s*?\/??>/i', '', $desc);
        $templateId = $this->request->param('templateId');
        $myAppId = $this->request->param('my_app_id/d');
        if(empty($myAppId)){
            return $this->error('我的应用不正确');
        }
        if(null === $myApp = AppModel::find($myAppId)){
            return $this->error('我的应用不正确');
        }
        $MiniappCloudLogic = new MiniappCloudLogic();
        try{            
            $res = $MiniappCloudLogic->overMiniapp([
                'appId' => $appId,
                'v'     => $v,
            ]);
            $AppVersionModel = new AppVersionModel();
            $AppVersionModel->save([
                'app_id' => $myAppId,
                'template' => $templateId,
                'v' => $v,
                'content' => $desc,
            ]);
            $myApp->status = 1;
            $myApp->save();
            return $this->success('更新成功');
        }catch (\Exception $e){
            return $this->error($e->getMessage());
        }
    }
    
}